<template>
  <div class="cinema-container">
    <search-bar />
    <!-- 加载失败 -->
    <empty v-if="error" :description="errorMsg" @tap="getList" />
    <!-- 正在加载 -->
    <empty v-else-if="loading" image-type="default" description="正在拼命加载" :show-button="false" />
    <!-- 正文 -->
    <div v-else>
      <van-sticky offset-top="1.22667rem" z-index="88">
        <van-dropdown-menu>
          <van-dropdown-item v-model="areaValue" :options="areaMenu" />
        </van-dropdown-menu>
      </van-sticky>

      <div class="cinema-wrap">
        <cinema-card v-for="cinema in areaCinemaList" :key="cinema.cinemaId" :cinema="cinema" />
      </div>
    </div>
  </div>
</template>

<script>
import SearchBar from '@/components/SearchBar'
import CinemaCard from '@/components/CinemaCard'
import { mapGetters, mapActions } from 'vuex'

export default {
  name: "cinemaPage",
  components: { SearchBar, CinemaCard },
  computed: {
    ...mapGetters([
      'currentCity',
      'cinemaList',
      'areaList'
    ]),
    areaCinemaList() {
      if (this.areaValue == 0) {
        return this.cinemaList
      }
      const areaInfo = this.areaMenu.find(v => v.value == this.areaValue)
      if (areaInfo != 'undefined') {
        return this.cinemaList.filter(({ regionName }) => regionName === areaInfo.text)
      }
      return []
    }
  },
  watch: {
    async currentCity(newCity, oldCity) {
      // oldCity 为 null，表示第一次改变（created时），所以不加载
      if (oldCity !== null) {
        this.$toast.loading('正在更新')
        const cinemaList = await this.getCinemaList()
        this.getAreaList(cinemaList)
        this.$notify({
          type: 'success',
          message: `为您推荐${cinemaList.length}家影院`
        })
        this.$toast.clear()
      }
    },
    // 监听区域 生成下拉菜单
    areaList(list) {
      if (list && list.length) {
        this.createAreaMenu(list)
      }
    }
  },
  data() {
    return {
      error: false,
      errorMsg: '数据加载失败',
      loading: true,
      areaMenu: [],
      areaValue: 0,
    }
  },
  created() {
    this.getList()
  },
  methods: {
    async getList() {
      try {
        this.error = false
        this.loading = true
        if (!this.currentCity) {
          await this.getCurrentCity()
        }
        await this.getCinemaList()
        this.getAreaList(this.cinemaList)
      } catch (error) {
        this.error = true
        this.errorMsg = error.message
      } finally {
        this.loading = false
      }
    },
    // 生成区域的下拉菜单
    createAreaMenu(areaList) {
      const areaMenu = areaList.map((item, index) => {
        return { text: item, value: ++index }
      })
      areaMenu.unshift({ text: '全城', value: 0 })
      this.areaMenu = areaMenu
    },
    ...mapActions({
      getCurrentCity: 'city/getCurrentCity',
      getCinemaList: 'cinema/getCinemaList',
      getAreaList: 'cinema/getAreaList',
    })
  },
};
</script>

<style lang="scss" scoped>
.cinema-container {
  .cinema-wrap {
    padding: 10px 0;
  }
}
</style>
